package com.mall.b2c.template.method;

import com.alibaba.fastjson.JSONObject;
import com.mall.b2c.bean.Principal;
import com.mall.b2c.hessian.TradeHessian;
import com.mall.common.util.AppContext;
import freemarker.template.TemplateMethodModel;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

import static com.mall.b2c.Constants.PRINCIPAL_SESSION_NAME;

/**
 * Created by lzx on 2015/5/11.
 */
@Repository
public class CountMethod  implements TemplateMethodModel{

    /**获取相应状态订单数量**/
    public final static String ORDER_STATUS = "order";

    @Resource private TradeHessian tradeHessian;

    @Override
    public Object exec(List arguments) throws TemplateModelException {

        if (arguments != null && !arguments.isEmpty() && arguments.get(0) != null) {
            String type = String.valueOf(arguments.get(0));
            if(type.equals(ORDER_STATUS)){
                String orderStatus = String.valueOf(arguments.get(1));
                return getOrderStatusCount(orderStatus, getMemberId());
            }
        }
        return null;
    }

    private Object getOrderStatusCount(String orderStatus, Long memberId) {
        return tradeHessian.orderCount(memberId, orderStatus);
    }

    /**
     * 将json转换成对象
     * @param json json值
     * @param clazz 转换的类型
     * @return
     */
    protected <T> T jsonToObj(String json, Class<T> clazz){
        return JSONObject.parseObject(json, clazz);
    }

    /**
     * 将json转换成list
     * @param json json值
     * @param clazz 转换的类型
     * @return
     */
    protected <T> List<T> jsonToList(String json, Class<T> clazz){
        return JSONObject.parseArray(json, clazz);
    }

    /**
     * 获取当前会员的帐号和id
     * @return
     */
    protected Principal getPrincipal(){
        Object obj = AppContext.getSessionAttr(PRINCIPAL_SESSION_NAME);
        if(obj != null){
            return (Principal) obj;
        }
        return null;
    }

    /**
     * 获取当前会员的id
     * @return
     */
    protected Long getMemberId(){
        Principal principal = getPrincipal();
        if(principal != null){
            return principal.getId();
        }
        return null;
    }
}
